/**
 * Copyright 2010 MiSSO4J author(s)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sjsso.app.service;

import static org.sjsso.Constant.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.sjsso.model.User;

public class Authentication {
	private String ssosrvurl;

	public Authentication(String ssosrvurl) {
		this.ssosrvurl = ssosrvurl;
	}

	public boolean isLoggedIn(User user) {
		String result = "";
		try {
			// check if user is indeed logged in
			URL url = new URL(ssosrvurl + "/verify?ts="
					+ (new Date()).getTime());
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();
			urlConnection.setRequestProperty("Cookie", "JSESSIONID="
					+ user.getToken());
			BufferedReader in = new BufferedReader(new InputStreamReader(
					urlConnection.getInputStream()));
			result = in.readLine().toString();
		} catch (IOException ioe) {

		}
		return result.equals("1");
	}

	private String checkNonce(String str) {
		String result = "";
		int nonceIndex = str.indexOf(NONCE + "=");
		if (nonceIndex >= 0) {
			try {
				URL url = new URL(ssosrvurl + "/cnonce?" + NONCE + "="
						+ str.substring(nonceIndex + 6));

				HttpURLConnection urlConnection = (HttpURLConnection) url
						.openConnection();
				BufferedReader in = new BufferedReader(new InputStreamReader(
						urlConnection.getInputStream()));

				result = in.readLine().toString();
			} catch (IOException ioe) {

			}
		}
		return result;
	}

	public User getUser(HttpServletRequest request) {
		String token = checkNonce(request.getQueryString());
		User user = null;
		if (token.length() > 0) {
			user = new User();
			user.setUsername(request.getParameter(UID));
			user.setToken(token);
		}
		return user;
	}
}
